﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using kwzx.Data;
using kwzx.Common;
using System.Threading;
using System.Diagnostics;
using System.Net;

namespace kwzx
{
    public partial class DW_fk : Form
    {
        //东屋  
        public const short ORDER_OK = 0x30;

        DataSet1TableAdapters.T_BMTableAdapter bm = new DataSet1TableAdapters.T_BMTableAdapter();
        DataSet1TableAdapters.T_GROUPTableAdapter group = new DataSet1TableAdapters.T_GROUPTableAdapter();
        DataSet1TableAdapters.V_jg_bmTableAdapter vjgbm = new DataSet1TableAdapters.V_jg_bmTableAdapter();

        string fkbk = "";
        public DW_fk(string fkbk1)
        {
            fkbk = fkbk1;
            InitializeComponent();
        }

        private void fk_Load(object sender, EventArgs e)
        {
            ksdateDateTimePicker.Text = "2013-05-01";
            jsdateDateTimePicker.Text = DateTime.Now.AddYears(30).ToShortDateString();

            // TODO: 这行代码将数据加载到表“dataSet1.CD_CardType”中。您可以根据需要移动或删除它。
            this.cD_CardTypeTableAdapter.Fill(this.dataSet1.CD_CardType);
            DataTable group_tb = group.GetDataBy_sjjg(0);
            for (int g = 0; g < group_tb.Rows.Count; g++)
            {
                TreeNode tn = new TreeNode();
                tn = treeView1.Nodes.Add(group_tb.Rows[g]["JGNAME"].ToString());
                tn.Text = group_tb.Rows[g]["jc"].ToString();
                tn.Tag = -1;
                tn.ToolTipText = "jg";
                tn.ImageIndex = 0;
                tn.SelectedImageIndex = 0;
                //  tn.Checked = true;
                //addJGTree(tn.Tag.ToString(), tn);
                addBMTree(group_tb.Rows[g]["GRPUP_ID"].ToString(), "0", tn);
            }
            //外协单位
            TreeNode tn1 = new TreeNode();
            tn1 = treeView1.Nodes.Add("外协单位");
            tn1.Text = "外协单位";
            tn1.Tag = "0";
            tn1.ToolTipText = "jg";
            tn1.ImageIndex = 0;
            tn1.SelectedImageIndex = 0;
            tn1.Checked = true;
            addJGTree(group_tb.Rows[0]["GRPUP_ID"].ToString(), tn1);
            treeView1.Nodes[0].ExpandAll();
            treeView1.SelectedNode = treeView1.Nodes[0].NextVisibleNode;
        }
        
        /// <summary>
        /// 递归加载addJGTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addJGTree(string fatherid, TreeNode pnode)
        {
            DataTable dt = group.GetDataBy_sjjg(int.Parse(fatherid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJJG] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "jg";
                    treeView1.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "jg";
                    pnode.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }

        /// <summary>
        /// 递归加载addBMTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addBMTree(string jgid, string fatherid, TreeNode pnode)
        {
            DataTable dt = bm.GetDataBy_grpup_id(int.Parse(jgid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJBM] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "bm";
                    treeView1.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "bm";
                    pnode.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }

        /// <summary>
        /// 树选中一结点时，在右侧的GridView中关联显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                int id = int.Parse(e.Node.Tag.ToString());
                string tooltiptext = e.Node.ToolTipText;

                if (tooltiptext.Equals("jg"))
                {
                    this.v_user_cardTableAdapter.FillBy_Allchild(this.dataSet1.V_user_card, int.Parse(treeView1.SelectedNode.Tag.ToString()));
                }
                else if (tooltiptext.Equals("bm"))
                {
                    this.v_user_cardTableAdapter.FillBy_DEPT_id(this.dataSet1.V_user_card, int.Parse(treeView1.SelectedNode.Tag.ToString()));
                }
            }

            string sql = " 1=1 ";
            if (this.radioButton1.Checked == true)
            {
                sql += "and CardId is NULL";
            }
            else
            {
                sql += "and CardId is not NULL";
            }

            vusercardBindingSource.Filter = sql;
            if (vusercardBindingSource.Count < 1)
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片; 
            }
        }

        /// <summary>
        /// 级联人员表及卡表信息显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void user_cardBindingSource_PositionChanged(object sender, EventArgs e)
        {
            if (vusercardBindingSource.Current != null)
            {
                string user_id = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();

                // TODO: 这行代码将数据加载到表“dataSet1.M_user_door_log”中。您可以根据需要移动或删除它。
                this.m_user_door_logTableAdapter.FillBy_user_id(this.dataSet1.M_user_door_log, Convert.ToInt32(user_id));

                //查出门号
                this.v_DW_doorTableAdapter.FillBy_user_id(this.dataSet1.V_DW_door, int.Parse(user_id));
                smTextBox.Text = "";
                for (int i = 0; i < this.dataSet1.V_DW_door.Rows.Count; i++)
                {
                    if (smTextBox.Text != "")
                    {
                        smTextBox.Text += ":" + dataSet1.V_DW_door.Rows[i]["bh"].ToString();
                    }
                    else
                    {
                        smTextBox.Text = dataSet1.V_DW_door.Rows[i]["bh"].ToString();
                    }
                }
                string users_id9 = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();
                string Imgpath = ((DataRowView)vusercardBindingSource.Current)["zp"].ToString(); ;
                if (!string.IsNullOrWhiteSpace(Imgpath))
                {
                    int x = Imgpath.IndexOf("ftp/") + 4;
                    string userImg = Imgpath.Substring(x, Imgpath.Length - x);   //ftp下载路径
                    int userImginfo = userImg.IndexOf("/") + 1;
                    string spath = SPicUtils.path + "\\";

                    string zpname = users_id9 + ".dat";
                    string kkzp = FileTran.DownloadFile(SPicUtils.path, zpname, userImg);
                    this.pictureBox1.Image = SPicUtils.PicConvert(kkzp);
                }
                else
                {
                    pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
                }

                string users_id = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();
                string CardID = ((DataRowView)vusercardBindingSource.Current)["CardID"].ToString();

                rybhTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["rybh"].ToString();
                zSXMTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["zsxm"].ToString();
                dEPT_idTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["jc"].ToString();
                if (((DataRowView)vusercardBindingSource.Current)["uby"].ToString() == "-1")
                {
                    dEPT_idTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["bmmc"].ToString();
                }
                dEPT_idTextBox.Text = dEPT_idTextBox.Text.Replace("(党委组织部)", "").Replace("(纪委办公室)", "");
                uBYTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["gsbm"].ToString();
                gzTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["gzmc"].ToString();
                gzTextBox.Text = gzTextBox.Text.Replace("（文秘、司机、厨师、保安、保洁、绿化）", "");
                xBTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["xb"].ToString();
                zWTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["zw"].ToString();
                dHTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["dh"].ToString();
                sfzhTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["sfzh"].ToString();
            }
            else
            {
                rybhTextBox.Text = "";
                zSXMTextBox.Text = "";
                dEPT_idTextBox.Text = "";
                uBYTextBox.Text = "";
                gzTextBox.Text = "";
                xBTextBox.Text = "";
                zWTextBox.Text = "";
                dHTextBox.Text = "";
                sfzhTextBox.Text = "";
            }
        }

        /// <summary>
        /// 搜索操作(查询功能)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {            
            //在所有记录中进行查询
            if (checkBox1.Checked)
            {
                v_user_cardTableAdapter.Fill(this.dataSet1.V_user_card);
            }

            textBox5.Text = "";
            string sql = " 1=1 ";
            if (this.textBox1.Text.ToString() != "")
            {
                sql += " and ZSXM like '%" + this.textBox1.Text.ToString() + "%'";
            }
            if (this.textBox2.Text.ToString() != "")
            {
                sql += "and sfzh like '%" + this.textBox2.Text.ToString() + "%'";
            }
            if (this.radioButton1.Checked == true)
            {
                sql += "and CardId is NULL";
            }
            else
            {
                sql += "and CardId is not NULL";
            }
            if (this.textBox3.Text.ToString() != "")
            {
                sql += " and kh like '%" + this.textBox3.Text.ToString() + "%'";
            }
            vusercardBindingSource.Filter = sql;

            user_cardBindingSource_PositionChanged(sender, e);
            this.user_cardDataGridView.Refresh();
            if (vusercardBindingSource.Count < 1)
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            }
        }

        private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            string sql = " 1=1 ";
            RadioButton rb = sender as RadioButton;
            if (rb.Name == "radioButton1")
            {
                sql += "and CardId is NULL";
                this.fkbutton.Enabled = true;
            }
            else if (rb.Name == "radioButton2")
            {
                sql += "and CardId is not NULL";
                //   this.fkbutton.Enabled = false;
            }

            vusercardBindingSource.Filter = sql;

            user_cardBindingSource_PositionChanged(sender, e);
            this.user_cardDataGridView.Refresh();
            if (vusercardBindingSource.Count < 1)
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            }
        }

        //起动服务
        private bool dwserver()
        {
            try
            {
                string exename = Properties.Settings.Default.exe_dwname;
                if (exename != "")
                {
                    string name1 = exename.Substring(exename.LastIndexOf("\\")+1, exename.Length - exename.LastIndexOf("\\")-1);
                    Process[] p = Process.GetProcessesByName(name1);
                     if (p.Length == 0)
                    {
                        p = Process.GetProcessesByName(name1.Replace(".exe", ""));
                    }
                    
                    if (p.Length == 0)
                    {

                        Process.Start(exename);
                  

                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("东屋写卡服务起动失败");
                return false;
            }
        }
        private void KillProcessExists()
        {
           
            try
            {
                string exename = Properties.Settings.Default.exe_dwname;
                if (exename != "")
                {
                    string name1 = exename.Substring(exename.LastIndexOf("\\") + 1, exename.Length - exename.LastIndexOf("\\") - 1);
                    Process[] p = Process.GetProcessesByName(name1);
                    if (p.Length == 0)
                    {
                        p = Process.GetProcessesByName(name1.Replace(".exe", ""));
                    }

                    if (p.Length >0)
                    {

                       
                                p[0].Kill();
                                p[0].Close();
                             
                      


                    }
                }
          

            }
            catch (Exception ex)
            {
              
            }
            
        }
        /// <summary>
        /// 东屋发卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fkbutton_Click(object sender, EventArgs e)
        {
            if (vusercardBindingSource.Current != null)
            {
                string kh = ((DataRowView)vusercardBindingSource.Current)["kh"].ToString();
                if (kh == "")
                {
                    MessageBox.Show("未分配卡号，请先分配卡！");
                    textBox3.Text = "";
                    textBox3.Focus();
                    return;
                }

                if (smTextBox.Text.Trim() == "")
                {
                    MessageBox.Show("没有分配房间,请先分配后写卡");
                    textBox3.Text = "";
                    textBox3.Focus();
                    return;
                }
                //起动写卡服务
                if (!dwserver())
                {
                    return;
                }

                DataSet1TableAdapters.M_user_door_logTableAdapter M_user_door_log = new DataSet1TableAdapters.M_user_door_logTableAdapter();
                
                try
                {
                    //更新卡号到卡表
                    DataSet1TableAdapters.K_CarddataTableAdapter kcad = new DataSet1TableAdapters.K_CarddataTableAdapter();
                    int user_id = int.Parse(((DataRowView)vusercardBindingSource.Current)["user_id"].ToString());
                    DateTime ksdate = DateTime.Parse(ksdateDateTimePicker.Value.ToShortDateString());
                    DateTime jsdate = DateTime.Parse(jsdateDateTimePicker.Value.ToShortDateString());

                    string SM = smTextBox.Text;
                    DateTime gxdate = DateTime.Now;
                    string zt = fkbk;
                    string lrz = Utils.CurrentUser.xm;
                    DateTime zzdate = DateTime.Now;
                    string czr = Utils.CurrentUser.xm;
                                        
                    //东屋
                    string dwip = Properties.Settings.Default.dwfkqip;
                    if (dwip == "127.0.0.1")
                    {
                        IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                        for (int i = 0; i != IpEntry.AddressList.Length; i++)
                        {
                            if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                            {
                                //MessageBox.Show(IpEntry.AddressList[i].ToString());
                                string myip = IpEntry.AddressList[0].ToString();
                                dwip = myip;
                            }
                        }
                    }
                    int mycnn = dwkey.TCPCONNECT(dwip);
                    if (mycnn == 48)
                    {
                        int CardID = 0;
                        //KeyType类型          Gname宾客姓名,GID:,证件号      RoomName:房间名称         卡片有效期   KStart,  KEnd   CardID:返回的卡号
                        //int dwid = dwkey.TCP_KEY(00, "GN2013", "999999999999999999", "C111", ksdate.ToString(), jsdate.ToString(), ref CardID);
                        int dwid = dwkey.TCP_KEY(00, zSXMTextBox.Text, sfzhTextBox.Text, SM, ksdate.ToString(), jsdate.ToString(), ref CardID);
                        dwkey.TCPDISCONNECT();
                        textBox5.Text = zSXMTextBox.Text + "写卡成功";
                        // MessageBox.Show("写卡成功！");
                    }
                    else
                    {
                        dwkey.TCPDISCONNECT();
                        MessageBox.Show("写卡失败！");
                        return;
                    }

                    //记录日志
                    M_user_door_log.InsertQuery(user_id, ksdate, jsdate, gxdate, kh, zt, SM, zzdate, czr);

                    // TODO: 这行代码将数据加载到表“dataSet1.M_user_door_log”中。您可以根据需要移动或删除它。
                    this.m_user_door_logTableAdapter.FillBy_user_id(this.dataSet1.M_user_door_log, Convert.ToInt32(user_id));

                   // Thread.Sleep(1000);
                    button2_Click(sender, e);
                    textBox3.Text = "";
                    textBox3.Focus();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gbbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void ksdateDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            int kkl = (((DateTime.Parse(jsdateDateTimePicker.Text) - DateTime.Parse(ksdateDateTimePicker.Text)).Days) / 365);
            textBox4.Text = kkl.ToString();
        }

        private void jsdateDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            int kkl = (((DateTime.Parse(jsdateDateTimePicker.Text) - DateTime.Parse(ksdateDateTimePicker.Text)).Days) / 365);
            textBox4.Text = kkl.ToString();
        }

        /// <summary>
        /// 读取东屋卡内信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //起动写卡服务
            if (!dwserver())
            {
                return;
            }

            textBox5.Text = "";
            string dwip = Properties.Settings.Default.dwfkqip;
            if (dwip == "127.0.0.1")
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                for (int i = 0; i != IpEntry.AddressList.Length; i++)
                {
                    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                    {
                        //MessageBox.Show(IpEntry.AddressList[i].ToString());
                        string myip = IpEntry.AddressList[0].ToString();
                        dwip = myip;
                    }
                }
            }

            int mycnn = dwkey.TCPCONNECT(dwip);
            if (mycnn == 48)
            {
                dwkey.PChar pc = new dwkey.PChar();
                byte KeyType = 00;
                dwkey.PChar GName = new dwkey.PChar();
                dwkey.PChar GID = new dwkey.PChar();
                dwkey.PChar RoomName = new dwkey.PChar();
                dwkey.PChar KStart = new dwkey.PChar();
                dwkey.PChar KEnd = new dwkey.PChar();
                int CardID = 0;
                byte myresult;

                try
                {
                    myresult = dwkey.TCP_CHECKCARD(ref KeyType, ref GName, ref GID, ref RoomName, ref KStart, ref KEnd, ref CardID);
                    dwkey.TCPDISCONNECT();
                    string GName1 = new string(GName.MyGetData).Replace("\0", "");
                    string GID1 = new string(GID.MyGetData).Replace("\0", "");
                    string KStart1 = new string(KStart.MyGetData).Replace("\0", "");
                    string KEnd1 = new string(KEnd.MyGetData).Replace("\0", "");
                    string RoomName1 = new string(RoomName.MyGetData).Replace("\0", "");

                    this.textBox5.Text = CardID.ToString() + "\r\n" + GName1 + "\r\n" + GID1 + "\r\n" + KStart1 + "\r\n" + KEnd1 + "\r\n" + RoomName1 + "\r\n";
                    if (RoomName1 != smTextBox.Text)
                    {
                        MessageBox.Show("房间号不一致,请检查");
                    }
                    if (myresult == ORDER_OK)
                    {

                    }
                    else
                    {
                        //确保数据库连接正确及有相应的授权。若数据库信息不正确，则去注册表里查询相应的配置，进行修改
                        //这里出错，一般情况是服务端（keyServer.exe）未启动；或者是服务端接收的数据有问题（dll文件不对应）
                        MessageBox.Show(myresult.ToString() + "Error");
                    }
                }
                catch
                {
                    dwkey.TCPDISCONNECT();
                    MessageBox.Show("00");
                }
            }
            else
            {
                dwkey.TCPDISCONNECT();
                MessageBox.Show("未连接到设备，请检查电源或线路！");
            }
        }

        /// <summary>
        /// 消除卡信息（将卡转变成移交卡）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            //起动写卡服务
            if (!dwserver())
            {
                return;
            }

            string dwip = Properties.Settings.Default.dwfkqip;
            if (dwip == "127.0.0.1")
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                for (int i = 0; i != IpEntry.AddressList.Length; i++)
                {
                    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                    {
                        //MessageBox.Show(IpEntry.AddressList[i].ToString());
                        string myip = IpEntry.AddressList[0].ToString();
                        dwip = myip;
                    }
                }
            }
            int mycnn = dwkey.TCPCONNECT(dwip);
            if (mycnn == 48)
            {
                dwkey.TCP_CHECKOUT("1101", true);
                dwkey.TCPDISCONNECT();
            }
            else
            {
                dwkey.TCPDISCONNECT();
            }
        }

        /// <summary>
        /// 快速授权操作，用DDS读卡器读卡号后，延迟1秒写授权信息。(这里要配二个读卡器)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.ToString() == "13")
            {
                button4_Click(sender, e);
                fkbutton.Focus();
                Thread.Sleep(1000);
                fkbutton_Click(sender, e);
            }
        }

        private void DW_fk_FormClosed(object sender, FormClosedEventArgs e)
        {
            KillProcessExists();
        }

        private void 取消当前房间权限ToolStripMenuItem_Click(object sender, EventArgs e)
        {
         
                    string m_name = ((DataRowView)vDWdoorBindingSource.Current)["name"].ToString();
           string  user_doorid = ((DataRowView)vDWdoorBindingSource.Current)["user_doorid"].ToString();
                    DialogResult dr = MessageBox.Show("是否取消 [" + m_name + "] 房间权限？", "取消提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                DataSet1TableAdapters.M_user_doorTableAdapter udorr = new DataSet1TableAdapters.M_user_doorTableAdapter();
                udorr.DeleteQuery(int.Parse(user_doorid));
                string user_id = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();

                // TODO: 这行代码将数据加载到表“dataSet1.M_user_door_log”中。您可以根据需要移动或删除它。
                this.v_DW_doorTableAdapter.FillBy_user_id(this.dataSet1.V_DW_door, int.Parse(user_id));
                MessageBox.Show("["+m_name + "]房间取消完成");
                
            }


        }
    }
}
